<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow" style="float: right;">
                <a-form :model="dataForm" layout="inline" size="small">
                    <a-form-item label="登记日期" label-col-flex="80px" style="width:270px">
                        <a-date-picker  popup-container="html"  class="bacClass" v-model="dataForm.beginDate" />
                    </a-form-item>
                    <a-form-item label="至" label-col-flex="80px" style="width:270px">
                        <a-date-picker  popup-container="html"  class="bacClass" v-model="dataForm.endDate" />
                    </a-form-item>
                    <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader" />
                    <a-form-item label="班次" label-col-flex="80px" style="width:270px">
                        <a-select popup-container="html"  class="bacClass" :allowClear="true" v-model="dataForm.workteam" :filter-option="false"
                            allow-search>
                            <a-option>A班</a-option>
                            <a-option>B班</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="员工工号" label-col-flex="80px" style="width:270px">
                        <a-input class="bacClass" v-model="dataForm.userCode" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="员工姓名" label-col-flex="80px" style="width:270px">
                        <a-input class="bacClass" disabled v-model="dataForm.userName" allow-clear></a-input>
                    </a-form-item>
                </a-form>
            </div>
            <div style="float: right;">
                <Toolbar :items="toolbarList" @add="addHandler" @select="selectHandler" @del="deleteHandler">
                </Toolbar>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
                @grid-ready="gridReady" style="height: calc(100% - 45px);" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                :rowData="tableDataList" :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
            <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
                @change="PageSize" @page-size-change="change" style="justify-content: center"
                :page-size="pagination.pageSize" :current="pagination.page" />
        </template>
        <a-drawer :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" height="80%" :visible="pageData.showAdd8"
            unmountOnClose @ok="sideOk" @cancel="pageData.showAdd8 = false" :width="400" cancel-text='关闭' ok-text='保存'>
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <a-form ref="formRef" :model="objectOP">
                <a-form-item label="记录单号" label-col-flex="80px">
                    <a-input disabled class="bacClass" v-model="objectOP.recordCode" />
                </a-form-item>
                <a-form-item label="登记日期" label-col-flex="80px">
                    <a-date-picker  popup-container="html"  style="width: 273px" class="bacClass" v-model="objectOP.recordDate" allow-clear />
                </a-form-item>
                <a-form-item label="奖捐类型" label-col-flex="80px">
                    <a-select popup-container="html"  class="bacClass" :loading="loading" :allowClear="true" @search="handleSearch"
                        v-model="objectOP.donationTypeName" :filter-option="false" allow-search @focus="focusSel"
                        @change="changeJJ">
                        <a-option v-for="item in pageData.nameList" :value="item['typeName']">{{
                            item['typeName']
                        }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="奖捐金额" label-col-flex="80px">
                    <a-input-number class="bacClass" v-model="objectOP.donationMoney" />
                </a-form-item>
                <!-- <a-form-item label="选择部门" label-col-flex="80px">
                    <CorporateSectorCascader style="width: 255px" :configCascader="configCascader"
                        @changeCascader="changeCascader" />
                </a-form-item> -->
                <CorporateSectorCascader style="margin-bottom: 8px !important;" ref="cascaderRefRef" v-model="objectOP.departmentName"
                    :configCascader="configCascader1" @changeCascader="changeCascader1" />
                <a-form-item label="班次" label-col-flex="80px" style="margin-top: -5px;">
                    <a-select popup-container="html"  class="bacClass" :allowClear="true" v-model="objectOP.workteam" :filter-option="false"
                        allow-search>
                        <a-option>A班</a-option>
                        <a-option>B班</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="员工工号" label-col-flex="80px">
                    <a-input class="bacClass" v-model="objectOP.userCode" />
                </a-form-item>
                <a-form-item label="员工姓名" label-col-flex="80px">
                    <a-input class="bacClass" v-model="objectOP.userName" />
                </a-form-item>
                <a-form-item label="备注" label-col-flex="80px">
                    <a-textarea class="bacClass" v-model="objectOP.remark" :max-length="400" allow-clear show-word-limit />
                </a-form-item>

            </a-form>
        </a-drawer>
    </pageTabelLayout>
</template>
<script setup lang="ts">
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";
import { ref, reactive } from "vue"
import { post, get } from "@/api/http"
import { localeText } from '@/api/aggridZw'

import Toolbar from "@/components/Toolbar.vue"
import { Message, Modal } from "@arco-design/web-vue"
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { FormInstance } from "@arco-design/web-vue/es/form";
import { pagingList } from "@/api/paging";
import dayjs from 'dayjs'
import { baseURL } from '../../../../api/axios.config'
import axios from "axios";
const toolbarList: any = ref(['查询', '新增', '删除'])
const cascaderRefRef: any = ref()
let configCascader = ref<{}>({
    corporateWidth: '215px', //公司宽度
    sectorWidth: '200px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '部门', //公司label
    sectorName: '选择部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
    corporateNameLabelWidth: '80px',
})
let configCascader1 = ref<{}>({
    corporateWidth: '280px', //公司宽度
    sectorWidth: '280px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'medium', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '部门', //公司label
    // sectorName: '选择部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
    corporateNameLabelWidth: '80px',
})
const changeCascader = (data: any) => {
    // const { corporateId } = data
    // whList.value = []
    // searchData.wh = ''
    // searchData.firm = corporateId
    // whService.getWarhouseList(corporateId, '原纱仓')
    dataForm.departmentName = data.corporateLabel
    // console.log(data);

}
const changeCascader1 = (data: any) => {
    objectOP.departmentCode = data.corporateId
    // objectOP.departmentName = data.corporateLabel
}
function PageSize(val: any) {
    pagination.page = val
    doRefresh();
}

function change(val: any) {
    pagination.pageSize = val
    doRefresh();
}
const headerShow = ref(true)
const tableDataList = ref([])


const gridOption = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
}
const localeText1: any = ref(localeText)
const tc = [
    {
        showRowGroup: 'hide_def',
        "headerName": "",
        "checkboxSelection": true,
        "headerCheckboxSelection": true,
        "pinned": "left",
        "width": 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: "left",
    },
    {
        headerName: '记录单号',
        field: 'recordCode',
        width: 150,
        filter: 'recordCode',
    },
    {
        headerName: '登记日期',
        field: 'recordDate',
        width: 150
    },
    {
        headerName: '部门编号',
        field: 'departmentCode',
        width: 150
    },
    {
        headerName: '部门名称',
        field: 'departmentName',
        width: 150
    },

    {
        headerName: '员工工号',
        field: 'userCode',
        width: 150
    },
    {
        headerName: '员工姓名',
        field: 'userName',
        width: 150
    },
    {
        headerName: '班次',
        field: 'workteam',
        width: 150
    },
    {
        headerName: '奖捐类型',
        field: 'donationTypeName',
        width: 150
    },
    {
        headerName: '奖捐金额',
        field: 'donationMoney',
        width: 150
    },
    {
        headerName: '备注',
        field: 'remark',
        width: 150
    },
    {
        headerName: "创建人",
        field: "createName",
        width: 150
    },
    {
        headerName: "创建时间",
        field: "createTime",
        width: 150
    },
    {
        headerName: "最后修改人",
        field: "updateName",
        width: 150
    },
    {
        headerName: "最后修改时间",
        field: "updateTime",
        width: 150
    },
    {
        headerName: '操作',
        field: 'id',
        pinned: 'right',
        width: 150,
        cellRenderer: {
            template: `
            <el-button style="color:#165dff;" @click="a" class="gesture" link>修改</el-button>
            `,
            setup(props: any) {
                const a = () => {
                    editHandler(props.params.data)
                }
                return {
                    a
                }
            }
        }
    }
]

const objectOP = reactive<{
    recordCode: any;
    recordDate: any
    donationTypeId: any
    donationTypeName: any
    donationMoney: any
    workteam: any
    userCode: any
    userName: any
    remark: any
    departmentCode: any
    departmentName: any
}>({
    recordCode: '',
    recordDate: '',
    donationTypeName: '',
    donationTypeId: null,
    donationMoney: null,
    workteam: '',
    userCode: '',
    userName: '',
    remark: '',
    departmentCode: null,
    departmentName: '',
});
const pageData = reactive<{
    sideTitle: string,
    showAdd8: boolean,
    pageLoading: boolean,
    nameList: any[],
    inputDisabled1: boolean,
    inputDisabled2: boolean
}>({
    sideTitle: "新增车间奖罚登记",
    showAdd8: false,
    pageLoading: false,
    nameList: [],
    inputDisabled1: false,
    inputDisabled2: false
});
const dataForm = reactive<{
    deleteState: any
    beginDate: any
    endDate: any
    workteam: any
    userCode: any
    userName: any
    departmentName: any
    size: any
    page: any
}>({
    deleteState: 0,
    beginDate: '',
    endDate: '',
    workteam: '',
    userCode: '',
    userName: '',
    departmentName: '',
    size: 10,
    page: 1
});

const editHandler = (record: any) => {
    // console.log(record, '睁开双眼做着梦');
    for (let key in record) {
        objectOP[key] = record[key]
    }
    let data = {
        corporateId: record.departmentCode,
        corporateLabel: record.departmentName,
    }
    // console.log(data, '你呀你一来一去在等待什么呢');
    pageData.sideTitle = '修改车间奖罚登记';
    pageData.showAdd8 = true;
    nextTick(() => {
        cascaderRefRef.value?.parentComponent(data)
    })
}
const addHandler = () => {
    for (var key in objectOP) {
        if (key == "id") {
            objectOP[key] = null;

        } else {
            objectOP[key] = '';
        }
    }
    pageData.sideTitle = "新增车间奖罚登记";
    pageData.showAdd8 = true;
    objectOP.recordDate = dayjs().format('YYYY-MM-DD')
    post({
        url: "/dwPc/WorkshopDonation/getCodeGenerate",
        data: {}
    }).then(({ code, data, message }: any) => {
        if (code === 200) {
            objectOP.recordCode = data
        }
    });
}
const selectHandler = () => {
    doRefresh()
}
const tabsKeys = ref(1)
const tabsChanges = (e: any) => {
    tabsKeys.value = e
    toolbarList.value = ['查询', '新增', '删除']
}

// 新增事件
const formRef = ref<FormInstance>();
const sideOk = () => {
    formRef.value?.validate().then((err) => {
        if (!err) {
            if (pageData.sideTitle === "新增车间奖罚登记") {
                post({
                    url: "/dwPc/WorkshopDonation/insert",
                    data: [objectOP]
                }).then((res: any) => {
                    if (res.code === 200) {
                        formRef.value?.resetFields();
                        pageData.showAdd8 = false;
                        Message.success({
                            content: "新增成功",
                            duration: 5000,
                        });
                        doRefresh();
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }
                })
            } else {
                post({
                    url: "/dwPc/WorkshopDonation/update",
                    data: [objectOP]
                }).then((res: any) => {
                    if (res.code === 200) {
                        formRef.value?.resetFields();
                        pageData.showAdd8 = false;
                        Message.success({
                            content: "修改成功",
                            duration: 5000,
                        });
                        doRefresh();
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }
                })
            }
        }
    })
}

// 下拉框下拉数据
const focusSel = () => {
    selCxAll({ "providerName": "" });
}
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
    if (value) {
        const ob = { providerName: value, deleteState: 0 }
        loading.value = true;
        selCxAll(ob);
        options.value = pageData.nameList;
        loading.value = false;
    } else {
        options.value = []
    }
};
function selCxAll(val: any) {
    post({
        url: "pieceData/fillDeductType/getList",
        data: { deleteState: 0 }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.nameList = data;
        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}
const changeJJ = () => {
    // let ob = ''
    pageData.nameList.filter((item: any) => {
        if (item.typeName == objectOP.donationTypeName) {
            return objectOP.donationTypeId = item.id
        }
    })
    // console.log(objectOP.donationTypeId, '灯光再亮也抱住你');
}

// 删除事件
const deleteHandler = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return;
    }
    Modal.confirm({
        title: "系统提示",
        content: "确认删除选中的数据?",
        onOk() {
            post({
                url: "/dwPc/WorkshopDonation/delete",
                data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: "删除成功",
                        duration: 5000,
                    });

                    pagination.page = 1
                    doRefresh();

                } else {
                    Message.error({
                        content: '删除失败',
                        duration: 5000,
                    });
                }

            });
        },
    });
};
// 查询事件
const total = ref(0);
const pagingList1: any = ref(pagingList)
function doRefresh() {
    pageData.pageLoading = true
    post({
        url: "/dwPc/WorkshopDonation/getPage",
        data: dataForm,
    })
        .then(({ data, code }: any) => {
            if (code === 200) {

                table.handleSuccess(data.list);
                gridOption.value.setRowData(data.list)
                total.value = data.total;

            }
        })
        .catch(console.log).finally(() => {
            pageData.pageLoading = false
        })
}

const { selectedRowKeys, onSelectionChange } = useRowSelection();
const pagination = usePagination(doRefresh);
const table = useTable();
const rowKey = useRowKey("id");
</script>
<script lang="ts">
export default {
    name: "WorkshopRewardAndPunishmentDemo",
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>

